package com.youku.component;

import java.util.HashMap;
import java.util.Map;

import org.junit.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.youku.component.connection.Connector;
import com.youku.component.notification.NotificationController;
import com.youku.component.procedure.Procedure;
import com.youku.expression.Position;
import com.youku.expression.environment.EnvironmentFactory;

/**
 * 项目
 * 
 * @author loda
 *
 */
public class Project extends BaseAttribute {

	private static final Logger logger = LoggerFactory.getLogger(Project.class);

	private Map<String, Connector> connectors = new HashMap<>();

	private Map<String, Template> templates = new HashMap<>();

	private String cronExpression;

	public String getCronExpression() {
		return cronExpression;
	}

	public void setCronExpression(String cronExpression) {
		this.cronExpression = cronExpression;
	}

	public void addTemplate(String key, Template template) {
		templates.put(key, template);
	}

	public Template getTemplate(String key) {
		return templates.get(key);
	}

	public void addConnector(String key, Connector connector) {
		connectors.put(key, connector);
	}

	public Connector getConnector(String key) {
		return connectors.get(key);
	}

	@Override
	public void run() {
		logger.info("===================project==================>开始执行测试项目{}", id);
		// 清除项目内部所有变量信息
		EnvironmentFactory.clearGlobal(id);
		super.run();
		logger.info("<===================project==================项目{}测试完成，发送测试报告", id);
		// 发送测试报告
		logger.debug("打印变量信息：\n{}", EnvironmentFactory.environmentToString());
		NotificationController.doNotify(id);
	}

	public TestSuite getSuite(String suiteId) {
		TestSuite suite = (TestSuite) getStepWithKey(suiteId);
		Assert.assertNotNull("找不到id为" + suiteId + "的测试用例组", suite);
		return suite;
	}

	public TestCase getCase(Position position) {
		TestCase testCase = getSuite(position.getSuiteId()).getCase(position.getCaseId());
		Assert.assertNotNull("找不到用例：" + position.toString(), testCase);
		return testCase;
	}

	public Procedure getProcedure(Position position, String procedureId) {
		Procedure p = getSuite(position.getSuiteId()).getCase(position.getCaseId()).getProcedure(procedureId);
		Assert.assertNotNull("找不到过程:" + position.toString() + "用例下的步骤：" + procedureId, p);
		return p;
	}

	@Override
	public void addVariable(String key, Object value) {
		// 为指定id的项目添加变量
		EnvironmentFactory.buildGlobal(id, key, value);
	}

	@Override
	public String getProjectId() {
		return id;
	}

	@Override
	public String getCaseId() {
		return null;
	}

	@Override
	public String getSuiteId() {
		return null;
	}
}
